package com.hc.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hc.entity.QcEquipment;
import com.hc.entity.QcEquipmentRecord;
import com.hc.entity.QcMonitor;
import com.hc.mapper.QcEquipmentMapper;
import com.hc.service.QcEquipmentRecordService;
import com.hc.service.QcMonitorService;
import com.hc.util.DateUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/li")
public class TeacherLiNeeds {

    @Autowired
    private QcEquipmentMapper qcEquipmentMapper;
    @Autowired
    private QcMonitorService qcMonitorService;
    @Autowired
    private QcEquipmentRecordService qcEquipmentRecordService;


    /*@GetMapping("/monitor")
    @ApiOperation("2月03日-2月26日 1.所有培养箱定期保养项目新增备注信息:校正温度及气体浓度达到正常工作范围2.所有培养箱更换耗材项目新增备注信息:已更换CODA ")
    public void monitor() {
        List<QcEquipment> qcEquipments = qcEquipmentMapper.selectList(Wrappers.lambdaQuery(new QcEquipment()).eq(QcEquipment::getClassifyId, "4"));
        List<Integer> collect = qcEquipments.stream().map(QcEquipment::getId).collect(Collectors.toList());
        String startTime = "2020-02-03 11:00:00";
        for (int i = 0; i < 24; i++) {
            List<QcMonitor> qcMonitors2 = new ArrayList<>();
            int finalI = i;
            collect.forEach(s -> {
                QcMonitor qcMonitor = new QcMonitor();
                qcMonitor.setEqId(s);
                qcMonitor.setRemark("校正温度及气体浓度达到正常工作范围");
                qcMonitor.setMaintenanceProjects("2");
                Date addAfterDate = DateUtil.getAddAfterDate(startTime, finalI * 24);
                qcMonitor.setMaintainTime(addAfterDate);
                qcMonitor.setCreateBy("1");
                qcMonitor.setCreateTime(addAfterDate);
                qcMonitors2.add(qcMonitor);
                QcMonitor qcMonitor2 = new QcMonitor();
                qcMonitor2.setEqId(s);
                qcMonitor2.setMaintainTime(addAfterDate);
                qcMonitor2.setCreateBy("1");
                qcMonitor2.setCreateTime(addAfterDate);
                qcMonitor2.setMaintenanceProjects("3");
                qcMonitor2.setRemark("已更换CODA");
                qcMonitors2.add(qcMonitor2);
            });
            qcMonitorService.saveBatch(qcMonitors2);
        }
    }*/

    @GetMapping("/addDigitalSignature")
    @ApiOperation("生成指定时间内的所有有巡检记录设备的签章记录")
    public void addDigitalSignature(@ApiParam("开始时间") @RequestParam("startTime") String startTime,
                                    @ApiParam("结束时间") @RequestParam("endTime") String endTime) {
        qcEquipmentRecordService.addDigitalSignature(startTime, endTime);
    }

    @GetMapping("/addRoutingInspection")
    @ApiOperation("按照指定日期区间和设备类型生成对应设备中的每个设备的巡检记录")
    @Transactional(rollbackFor = Exception.class)
    public void addRoutingInspection(@ApiParam("设备类型") @RequestParam("classifyId") String classifyId,
                                     @ApiParam("开始时间,yyyy-MM-dd格式") @RequestParam("beginDateStr") String beginDateStr,
                                     @ApiParam("结束时间,yyyy-MM-dd格式") @RequestParam("endDateStr") String endDateStr) throws Exception {
        //计算开始时间和结束时间间隔的天数
        Long dateNum = countDate(beginDateStr, endDateStr);
        //查询所有设备类型的设备
        List<QcEquipment> qcEquipments = qcEquipmentMapper.selectList(Wrappers.lambdaQuery(new QcEquipment())
                .eq(QcEquipment::getClassifyId, classifyId));
        //获取所有的设备id
        List<Integer> ids = qcEquipments.stream()
                .map(QcEquipment::getId)
                .collect(Collectors.toList());
        List<QcEquipmentRecord> list = new ArrayList<>();
        ////如果设备类型是工作台，工作台的巡检记录和其他设备的不一样，所以单独处理
        if (StringUtils.equals("9", classifyId)) {
            for (int j = 0; j < ids.size(); j++) {
                //获取当前下标下的设备id
                Integer id = ids.get(j);
                for (int i = 0; i <= dateNum; i++) {
                    //创建操作前巡检记录对象和操作后巡检记录对象
                    QcEquipmentRecord qcEquipmentRecordBefore = new QcEquipmentRecord();
                    QcEquipmentRecord qcEquipmentRecordAfter = new QcEquipmentRecord();
                    //设置工作台操作前和操作后的巡检记录对应的设备id
                    qcEquipmentRecordBefore.setEqId(id);
                    qcEquipmentRecordAfter.setEqId(id);
                    //设置工作台操作前和操作后的巡检记录的操作类型为ICSI
                    qcEquipmentRecordBefore.setWorkbenchOperationType("1");
                    qcEquipmentRecordAfter.setWorkbenchOperationType("1");
                    //设置工作台操作前和操作后的巡检记录的工作台操作模式是操作前还是操作后
                    qcEquipmentRecordBefore.setWorkbenchOperationPattern("1");
                    qcEquipmentRecordAfter.setWorkbenchOperationPattern("2");
                    //设置工作台操作前和操作后的巡检记录的油量为高
                    qcEquipmentRecordBefore.setOilMass("1");
                    qcEquipmentRecordAfter.setOilMass("1");
                    //设置工作台操作前和操作后的巡检记录的操作臂行程为正常
                    qcEquipmentRecordBefore.setMotionArm("1");
                    qcEquipmentRecordAfter.setMotionArm("1");
                    //设置工作台操作前和操作后的巡检记录的温板温度为正常
                    qcEquipmentRecordBefore.setWenBoard("1");
                    qcEquipmentRecordAfter.setWenBoard("1");
                    //设置工作台操作前和操作后的巡检记录的是否添加矿物油为是
                    qcEquipmentRecordBefore.setMineralOil("1");
                    qcEquipmentRecordAfter.setMineralOil("1");
                    //设置工作台操作前和操作后的巡检记录的光源为正常
                    qcEquipmentRecordBefore.setLightSource("1");
                    qcEquipmentRecordAfter.setLightSource("1");
                    //设置创建时间，根据开始和结束时间相隔的天数，创建时间也是往后一天一天递增的，直到结束时间为止
                    //将开始时间转化成localDateTime类型，用于之后计算巡检记录的时间用
                    LocalDateTime localDateTimeOnWork = changeStrToDateTime(beginDateStr);
                    LocalDateTime localDateTimeOffWork = changeStrToDateTime(beginDateStr);
                    LocalDateTime createTimeBefore = localDateTimeOnWork.plusDays(i);
                    LocalDateTime createTimeAfter = localDateTimeOffWork.plusDays(i);
                    //设置操作前巡检时间为9点
                    createTimeBefore.plusHours(9);
                    //设置操作后巡检的时间为11点
                    createTimeAfter.plusHours(11);
                    //设置工作台操作前和操作后的巡检记录的创建时间
                    Date dateOnBefore = changeLocalDateTimeToDate(createTimeBefore);
                    Date dateOnAfter = changeLocalDateTimeToDate(createTimeAfter);
                    qcEquipmentRecordBefore.setCreateTime(dateOnBefore);
                    qcEquipmentRecordAfter.setCreateTime(dateOnAfter);
                    //设置工作台操作前和操作后的巡检记录的巡检人
                    qcEquipmentRecordBefore.setCreateBy("3");
                    qcEquipmentRecordAfter.setCreateBy("3");
                    //设置工作台操作前和操作后的巡检记录的巡检方式为扫码
                    qcEquipmentRecordBefore.setInspectionWay("1");
                    qcEquipmentRecordAfter.setInspectionWay("1");
                    //设置工作台操作前和操作后的巡检记录的操作批次
                    long l = System.currentTimeMillis();
                    qcEquipmentRecordBefore.setWorkbenchOperationBatch("" + l);
                    qcEquipmentRecordAfter.setWorkbenchOperationBatch("" + l);
                    list.add(qcEquipmentRecordBefore);
                    list.add(qcEquipmentRecordAfter);
                }
            }
            //如果设备类型是其他巡检设备
        } else if (StringUtils.equals("1", classifyId) || StringUtils.equals("4", classifyId)
                || StringUtils.equals("5", classifyId) || StringUtils.equals("6", classifyId)
                || StringUtils.equals("7", classifyId) || StringUtils.equals("11", classifyId)
                || StringUtils.equals("2", classifyId)) {
            for (int j = 0; j < ids.size(); j++) {
                //获取当前下标下的设备id
                Integer id = ids.get(j);
                for (int i = 0; i <= dateNum; i++) {
                    //创建上班巡检记录对象和下班巡检记录对象
                    QcEquipmentRecord qcEquipmentRecordOnWork = new QcEquipmentRecord();
                    QcEquipmentRecord qcEquipmentRecordOffWork = new QcEquipmentRecord();
                    //设置巡检记录的公有属性值
                    //设置设备id
                    qcEquipmentRecordOnWork.setEqId(id);
                    qcEquipmentRecordOffWork.setEqId(id);
                    //设置运行状态
                    qcEquipmentRecordOnWork.setRunningStatus("1");
                    qcEquipmentRecordOffWork.setRunningStatus("1");
                    //设置创建时间，根据开始和结束时间相隔的天数，创建时间也是往后一天一天递增的，直到结束时间为止
                    //将开始时间转化成localDateTime类型，用于之后计算巡检记录的时间用
                    LocalDateTime localDateTimeOnWork = changeStrToDateTime(beginDateStr);
                    LocalDateTime localDateTimeOffWork = changeStrToDateTime(beginDateStr);
                    LocalDateTime createTimeOnWork = localDateTimeOnWork.plusDays(i);
                    LocalDateTime createTimeOffWork = localDateTimeOffWork.plusDays(i);
                    //设置上班巡检时间为9点
                    createTimeOnWork.plusHours(9);
                    //设置下班巡检的时间为18点
                    createTimeOffWork.plusHours(18);
                    //设置上班巡检和下班巡检的时间
                    Date dateOnWork = changeLocalDateTimeToDate(createTimeOnWork);
                    Date dateOffWork = changeLocalDateTimeToDate(createTimeOffWork);
                    qcEquipmentRecordOnWork.setCreateTime(dateOnWork);
                    qcEquipmentRecordOffWork.setCreateTime(dateOffWork);
                    //设置巡检人
                    qcEquipmentRecordOnWork.setCreateBy("3");
                    qcEquipmentRecordOffWork.setCreateBy("3");
                    //设置工作状态，是上班巡检还是下班巡检
                    qcEquipmentRecordOnWork.setWorkStatus("1");
                    qcEquipmentRecordOffWork.setWorkStatus("2");
                    //设置巡检方式为扫码
                    qcEquipmentRecordOnWork.setInspectionWay("1");
                    qcEquipmentRecordOffWork.setInspectionWay("1");
                    //如果设备类型是冰箱,设置冰箱的冷冻温度和冷藏温度
                    if (StringUtils.equals("1", classifyId)) {
                        //设置冷冻温度和冷藏温度，因为只有1号和5号冰箱才有冷冻温度，所以其他冰箱不设置冷冻温度
                        qcEquipmentRecordOnWork.setColdTemperature("5");
                        qcEquipmentRecordOffWork.setColdTemperature("5");
                        //如果是1号和5号冰箱，设置冷冻温度
                        if (148 == id || 151 == id) {
                            qcEquipmentRecordOnWork.setFreezingTemperature("-20");
                            qcEquipmentRecordOffWork.setFreezingTemperature("-20");
                        }
                        //如果设备是胚胎库
                    } else if (StringUtils.equals("2", classifyId)) {
                        //胚胎库没有运行状态，所以设置为null
                        qcEquipmentRecordOnWork.setRunningStatus(null);
                        qcEquipmentRecordOffWork.setRunningStatus(null);
                        //设置监控系统为正常
                        qcEquipmentRecordOnWork.setMonitoringSystem("1");
                        qcEquipmentRecordOffWork.setMonitoringSystem("1");
                        //设置液氮罐锁状态为正常
                        qcEquipmentRecordOnWork.setCanisterLock("1");
                        qcEquipmentRecordOffWork.setCanisterLock("1");
                        //设置液氮罐温度状态为正常
                        qcEquipmentRecordOnWork.setCanisterTemperature("1");
                        qcEquipmentRecordOffWork.setCanisterTemperature("1");
                    }
                    list.add(qcEquipmentRecordOnWork);
                    list.add(qcEquipmentRecordOffWork);
                }
            }
        } else {
            throw new Exception("输入设备类型有误");
        }
        //批量添加巡检记录
        qcEquipmentRecordService.saveBatch(list);
    }


    /**
     * 将LocalDateTime类型转化成Date类型
     *
     * @param localDateTime
     * @return
     */
    private Date changeLocalDateTimeToDate(LocalDateTime localDateTime) {
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zdt = localDateTime.atZone(zoneId);
        Date date = Date.from(zdt.toInstant());
        return date;
    }

    /**
     * 将yyyy-MM-dd格式的字符串转化成LocalDateTime类型
     *
     * @param dateStr
     * @return
     */
    private LocalDateTime changeStrToDateTime(String dateStr) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate localDate = LocalDate.parse(dateStr, df);
        LocalDateTime localDateTime = localDate.atStartOfDay();
        return localDateTime;
    }

    /**
     * 计算开始时间和结束时间间隔了多少天
     *
     * @param beginDateStr
     * @param endDateStr
     * @return
     */
    private Long countDate(String beginDateStr, String endDateStr) {
        LocalDateTime beginTime = changeStrToDateTime(beginDateStr);
        LocalDateTime endTime = changeStrToDateTime(endDateStr);
        Duration duration = Duration.between(beginTime, endTime);
        long l = duration.toDays();
        return l;
    }

    @GetMapping("/insertEquipmentRecord")
    @ApiOperation("根据设备存放位置和设备类型添加对应设备指定日期的设备上班巡检记录")
    @Transactional(rollbackFor = Exception.class)
    public void insertEquipmentRecord(@ApiParam("设备存放位置") @RequestParam("localtion") String localtion,
                                      @ApiParam("设备类型") @RequestParam("classifyId") String classifyId,
                                      @ApiParam("时间") @RequestParam("date") String date,
                                      @ApiParam("巡检人id") @RequestParam("userId") String userId,
                                      @ApiParam("工作状态") @RequestParam("workStatus") String workStatus) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date dateNow = sdf.parse(date);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dateNow);
        calendar.set(Calendar.HOUR_OF_DAY, 8);
        calendar.set(Calendar.MINUTE, 30);
        Date time = calendar.getTime();
        List<QcEquipment> qcEquipments = qcEquipmentMapper.selectList(Wrappers.lambdaQuery(new QcEquipment())
                .eq(QcEquipment::getClassifyId, classifyId)
                .eq(QcEquipment::getLocation, localtion));
        List<Integer> ids = qcEquipments.stream().map(QcEquipment::getId)
                .collect(Collectors.toList());
        List<QcEquipmentRecord> list = new ArrayList<>();
        ids.forEach(id -> {
            QcEquipmentRecord qcEquipmentRecord = new QcEquipmentRecord();
            //设置设备id
            qcEquipmentRecord.setEqId(id);
            //设置设备运行状态为正常
            qcEquipmentRecord.setRunningStatus("1");
            //设置巡检时间
            qcEquipmentRecord.setCreateTime(time);
            //设置巡检人
            qcEquipmentRecord.setCreateBy(userId);
            //设置工作状态
            qcEquipmentRecord.setWorkStatus(workStatus);
            //设置巡检方式
            qcEquipmentRecord.setInspectionWay("1");
            //个别设备的巡检记录需要添加特殊字段的值
            //冰箱
            if (StringUtils.equals("1", classifyId)) {
                qcEquipmentRecord.setColdTemperature("5");
                qcEquipmentRecord.setFreezingTemperature("-18");
            //液氮罐
            } else if (StringUtils.equals("2", classifyId)) {
                qcEquipmentRecord.setRunningStatus(null);
                qcEquipmentRecord.setMonitoringSystem("1");
                qcEquipmentRecord.setCanisterLock("1");
                qcEquipmentRecord.setCanisterTemperature("1");
            }
            list.add(qcEquipmentRecord);
        });
        qcEquipmentRecordService.saveBatch(list);
    }

    public static void main(String[] args) {

    }

}
